package com.scut.fy.gateway.service.impl;

import com.scut.fy.common.core.util.Assert;
import com.scut.fy.common.core.util.BeanUtils;
import com.scut.fy.gateway.fegin.FyAdminFeign;
import com.scut.fy.gateway.model.dto.SysRoleDto;
import com.scut.fy.gateway.model.dto.SysUserDto;
import com.scut.fy.gateway.service.SysRoleService;
import com.scut.fy.gateway.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author JY
 * @version 1.0
 * @date 2021/9/14
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    private static final Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysUserService sysUserService;

    @Qualifier("fyAdminFeignFallback")
    @Autowired
    private FyAdminFeign fyAdminFeign;
    @Override
    public List<SysRoleDto> findRolesByUser(long userId) {

        // 先查redis里面有没有这个用户的数据
        SysUserDto userDto = sysUserService.findUserDtoByUserId(userId);
        List<SysRoleDto> roleDtos = new ArrayList<>();
        // 如果redis有数据就用redis里面的
        if (null != userDto) {
            if (userDto.getRoles().size() > 0) {
                roleDtos = userDto.getRoles();
            } else {
                roleDtos = BeanUtils.mapsToBeans(
                        fyAdminFeign.findRolesByUserId(userId).getData(), SysRoleDto.class);
                userDto.setRoles(roleDtos);
                redisTemplate.opsForValue().set("FY_GATEWAY_SYS_USER" + String.valueOf(userId),
                        userDto,
                        60*30);
            }

        } else {
            log.error("用户不存在");
        }
        return roleDtos;
    }

    @Override
    public List<SysRoleDto> findRolesByUser(String userName) {

        Assert.notNull(userName, "用户名不能为空");
        // 先查redis里面有没有这个用户的数据
        SysUserDto userDto = sysUserService.findUserDtoByUserName(userName);
        List<SysRoleDto> roleDtos = new ArrayList<>();
        // 如果redis有数据就用redis里面的
        if (null != userDto) {
            if (userDto.getRoles().size() > 0) {
                roleDtos = userDto.getRoles();
            } else {
                roleDtos = BeanUtils.mapsToBeans(
                        fyAdminFeign.findRolesByUserName(userName).getData(), SysRoleDto.class);
                userDto.setRoles(roleDtos);
                redisTemplate.opsForValue().set("FY_GATEWAY_SYS_USER" + String.valueOf(userName),
                        userDto,
                        60*30);
            }

        } else {
            log.error("用户不存在");
        }
        return roleDtos;
    }
}
